package com.lindenvalley.ch;

import java.util.Calendar;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import com.lindenvalley.ch.adapters.AbstractWeekTaskAdapter;
import com.lindenvalley.ch.adapters.PeriodWeekTaskAdapter;
import com.lindenvalley.ch.adapters.RenameWeekTaskAdapter;
import com.lindenvalley.ch.adapters.SearchWeekTaskAdapter;
import com.lindenvalley.ch.content.User;
import com.lindenvalley.ch.content.Week;
import com.lindenvalley.ch.content.Weeks;
import com.lindenvalley.ch.network.WorkServer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.Toast;

public class SearchActivity extends Activity implements OnItemSelectedListener, OnItemClickListener, View.OnClickListener{
	private final String TAG = getClass().getSimpleName();
	private SearchWeekTaskAdapter searchAdapter;
	private RenameWeekTaskAdapter fromYearAdapter, toYearAdapter;
	private PeriodWeekTaskAdapter periodAdapter;
	private Weeks weeks;
	private User user;
	private Serializer serializer;
	private ListView lv;
	private TableLayout tableLayout;
	private LinearLayout linearLayout;
	private Spinner fromWeekSpiner, toWeekSpiner, fromYearSpiner, toYearSpiner;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		weeks = WorkServer.getInstance().getWeeks();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_activity);
		user = WorkServer.getInstance().getUser();
		serializer = new Persister();
		tableLayout = (TableLayout) findViewById(R.id.tableLayout1);
		linearLayout = (LinearLayout) findViewById(R.id.linearLayout2);

		ImageView viewRename = (ImageView)findViewById(R.id.imageViewRename);
		viewRename.setOnClickListener(this);
		lv = (ListView) findViewById(R.id.searchListView1);
		searchAdapter = new SearchWeekTaskAdapter(this,R.layout.search_row, weeks);
		periodAdapter = new PeriodWeekTaskAdapter(this,R.layout.search_row, null);
		fromYearAdapter = new RenameWeekTaskAdapter(this,R.layout.search_years_row, null);
		toYearAdapter = new RenameWeekTaskAdapter(this,R.layout.search_years_row, null);
		lv.setAdapter(searchAdapter);
		lv.setOnItemClickListener(this);
		
		fromWeekSpiner = (Spinner) findViewById(R.id.fromWeek);
		toWeekSpiner = (Spinner) findViewById(R.id.toWeek);
		fromYearSpiner = (Spinner) findViewById(R.id.fromYear);
		toYearSpiner = (Spinner) findViewById(R.id.toYear);
		Spinner years = (Spinner) findViewById(R.id.years);
		fromWeekSpiner.setOnItemSelectedListener(this);
		fromWeekSpiner.setAdapter(fromYearAdapter);
		toWeekSpiner.setOnItemSelectedListener(this);
		toWeekSpiner.setAdapter(toYearAdapter);
		fromYearSpiner.setOnItemSelectedListener(this);
		toYearSpiner.setOnItemSelectedListener(this);
		years.setOnItemSelectedListener(this);
		
		years.setSelection(Calendar.getInstance().get(Calendar.YEAR) - 2000);
		Button buttonRename = (Button)findViewById(R.id.searchButtonApply);
		buttonRename.setOnClickListener(this);
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		int id = arg0.getId();
		AbstractWeekTaskAdapter adapter = null;
		switch (id) {
		// if selected start year
		case R.id.fromYear:
			adapter = fromYearAdapter;
			break;
		//if selected start week
		case R.id.fromWeek:
			Week weekFrom = fromYearAdapter.getItem(fromWeekSpiner.getSelectedItemPosition());
			long startPeriodDate = weekFrom.getStartDate();
			periodAdapter.setStartPeriodDate(startPeriodDate);
			break;
		// if selected end year
		case R.id.toYear:
			adapter = toYearAdapter;
			break;
		// if selected end week
		case R.id.toWeek:
			Week weekTo = toYearAdapter.getItem(toWeekSpiner.getSelectedItemPosition());
			long endPeriodDate = weekTo.getStartDate();
			periodAdapter.setEndPeriodDate(endPeriodDate);
			break;
		// if selected current year
		case R.id.years:
			adapter = searchAdapter;			
			break;

		}
		
		if (adapter != null){
			int position = arg2;
			int year = 2000 + position;
			WeekAsyncTask task = new WeekAsyncTask();
			task.execute(new Object[]{year,adapter});

		}
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intentResult = new Intent();
		intentResult.putExtra(TagesberichtActivity.RESULT_WEEK_DATA, weeks.getWeekCount() - arg2 - 1);
		setResult(Activity.RESULT_OK, intentResult);
		
		finish();
		
	}
	
	class WeekAsyncTask extends AsyncTask<Object, Object, Object>{
		
		ProgressDialog dialog;
		boolean isCancel = false;
		AbstractWeekTaskAdapter adapter;
		
		@Override
		protected Object doInBackground(Object... params) {
			if (params != null && params.length >=2){
				Integer year = (Integer)params[0];
				adapter = (AbstractWeekTaskAdapter) params[1]; 
				String data = WorkServer.getInstance().getTasks(user.getUserId(), year);
				try {
					Weeks mWeeks = serializer.read(Weeks.class, data);
					if (adapter instanceof SearchWeekTaskAdapter){
						WorkServer.getInstance().setWeeks(mWeeks);
						weeks = mWeeks;
					}
					adapter.setData(mWeeks);
					if (adapter instanceof RenameWeekTaskAdapter){
						int fromYear = fromYearSpiner.getSelectedItemPosition() + 2000;
						int toYear = toYearSpiner.getSelectedItemPosition() + 2000;
						data = WorkServer.getInstance().getWeekPeriod(fromYear, toYear);
						mWeeks = serializer.read(Weeks.class, data);
						periodAdapter.setData(mWeeks);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			adapter.notifyDataSetChanged();
			if (adapter instanceof RenameWeekTaskAdapter){
				Week weekFrom = fromYearAdapter.getItem(fromWeekSpiner.getSelectedItemPosition());
				if (weekFrom != null){
					long startPeriodDate = weekFrom.getStartDate();
					periodAdapter.setStartPeriodDate(startPeriodDate);
				}
				
				Week weekTo = toYearAdapter.getItem(toWeekSpiner.getSelectedItemPosition());
				if (weekTo != null){
					long endPeriodDate = weekTo.getStartDate();
					periodAdapter.setEndPeriodDate(endPeriodDate);
				}
				
				periodAdapter.notifyDataSetChanged();
			}
			if (dialog != null && dialog.isShowing()){
	        	 try{
	        		 dialog.dismiss();
	        	 }catch (IllegalArgumentException ex){
	        		 Log.i(TAG, " ----- > Error to close progress dialog wthen device is rotating");
	        	 }
	         }
			
		}

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(SearchActivity.this);
			dialog.setMessage("Empfange Daten vom Server....");
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					isCancel = true;
				}
			});
			dialog.show();
		}
		
	}
	
	class RenameAusbildAsyncTask extends AsyncTask<Long, Object, Object>{
		
		ProgressDialog dialog;
		boolean isCancel = false;
		
		@Override
		protected Object doInBackground(Long... params) {
			if (params != null && params.length >=2){
				Long fromTimeStamp = (Long)params[0];
				Long toTimeStamp = (Long)params[1];
				String value = String.valueOf(params[2]);
				WorkServer.getInstance().changeAusbildNumberPeriod(fromTimeStamp, toTimeStamp, value);
				long fromYear = params[3];
				long toYear = params[4];
				String data = WorkServer.getInstance().getWeekPeriod((int)fromYear, (int)toYear);
				Weeks mWeeks;
				try {
					mWeeks = serializer.read(Weeks.class, data);
					periodAdapter.setData(mWeeks);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			periodAdapter.notifyDataSetChanged();
			if (dialog != null && dialog.isShowing()){
	        	 try{
	        		 dialog.dismiss();
	        	 }catch (IllegalArgumentException ex){
	        		 Log.i(TAG, " ----- > Error to close progress dialog wthen device is rotating");
	        	 }
	         }
			if (!isCancel){
				Toast.makeText(SearchActivity.this, "SUCCESS", Toast.LENGTH_SHORT);
			}
			
		}

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(SearchActivity.this);
			dialog.setMessage("Synchronisierung mit dem Server...");
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					isCancel = true;
				}
			});
			dialog.show();
		}
		
	}


	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch(id){
			case R.id.imageViewRename:
				if (tableLayout.getVisibility() != View.VISIBLE){
					linearLayout.setVisibility(View.GONE);
					tableLayout.setVisibility(View.VISIBLE);
					if (lv != null){
						lv.setOnItemClickListener(null);
						lv.setAdapter(periodAdapter);
					}
					
				} else {
					tableLayout.setVisibility(View.GONE);
					linearLayout.setVisibility(View.VISIBLE);
					if (lv != null){
						lv.setOnItemClickListener(SearchActivity.this);
						lv.setAdapter(searchAdapter);
					}
				}
				break;
				
			case R.id.searchButtonApply:
				int fromYear = fromYearSpiner.getSelectedItemPosition() + 2000;
				int toYear = toYearSpiner.getSelectedItemPosition() + 2000;
				Week fromWeek = fromYearAdapter.getItem(fromWeekSpiner.getSelectedItemPosition());
				Week toWeek = toYearAdapter.getItem(toWeekSpiner.getSelectedItemPosition());
				long fromTimeStamp = fromWeek.getStartDate();
				long toTimeStamp = toWeek.getStartDate();
				EditText renameValueView = (EditText)findViewById(R.id.editTextAusbild);
				long value = 0;
				try{
					value = Long.parseLong(renameValueView.getText().toString());
				} catch (NumberFormatException ex){
					ex.printStackTrace();
				}
				Long[] params = new Long[5];
				params[0] = fromTimeStamp;
				params[1] = toTimeStamp;
				params[2] = value;
				params[3] = (long)fromYear;
				params[4] = (long)toYear;
				RenameAusbildAsyncTask task = new RenameAusbildAsyncTask();
				task.execute(params);
				
				break;
		}
		
	}
	
	

}
